#include "recbox.h"
#include "ui_recbox.h"

RecBox::RecBox(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::RecBox)
    ,row(1)
    ,col(4)
{
    ui->setupUi(this);
}

RecBox::~RecBox()
{
    delete ui;
}

void RecBox::initRecBoxUi(QJsonArray data, int row)
{

    // ...
    imageList = data;

    // 默认显⽰第0组
    currentIndex = 0;

    // 计算总共有⼏组图⽚，ceil表⽰向上取整
    count = ceil(imageList.size()/col);

    // 如果是两⾏，说明当前RecBox是主界⾯上的supplyMusicBox
    if(2 == row)
    {
        this->row = row;
        this->col = 8;
    }
    else
    {
        // 否则：只有⼀⾏，为主界⾯上recMusicBox
        ui->recListDown->hide();
    }


    // 图⽚保存起来
    imageList = data;
    // 往RecBox中添加图⽚
    createRecItem();

}

void RecBox::createRecItem()
{
    for(int i = 0; i < col; ++i)
    {
        RecBoxItem* item = new RecBoxItem();
        // 设置⾳乐图⽚与对应⽂本
        QJsonObject obj = imageList[i].toObject();
        item->setText(obj.value("text").toString());
        item->setImage(obj.value("path").toString());
        if(i >= col/2 && row == 2)
        {
            ui->recListDownHLayout->addWidget(item);
        }
        else
        {
            ui->recListUpHLayout->addWidget(item);
        }
    }

}


void RecBox::on_btUp_clicked()
{
    // 点击btUp按钮，显⽰前⼀组图⽚，如果已经是第⼀组图⽚，显⽰最后⼀组
    currentIndex--;
    if(currentIndex < 0)
    {
        currentIndex = 0;
    }

    createRecBoxItem();
}


void RecBox::on_btDown_clicked()
{
    // 点击btDown按钮，显⽰下⼀组图⽚，如果已经是最后⼀组图⽚，显⽰第0组
    currentIndex++;
    if(currentIndex >= count)
    {
        currentIndex = 0;
    }
    createRecBoxItem();
}

void RecBox::createRecBoxItem()
{
    // 溢出掉之前旧元素
    QList<RecBoxItem*> recUpList = ui->recListUp->findChildren<RecBoxItem*>();
    for(auto e : recUpList)
    {
        ui->recListUpHLayout->removeWidget(e);
        delete e;
    }
    QList<RecBoxItem*> recDownList = ui->recListDown->findChildren<RecBoxItem*>();
    for(auto e : recDownList)
    {
        ui->recListDownHLayout->removeWidget(e);
        delete e;
    }
    // 创建RecBoxItem对象，往RecBox中添加
    int index = 0;
    for(int i = currentIndex*col; i < col + currentIndex*col; ++i)
    {
        RecBoxItem* item = new RecBoxItem();
        // 设置⾳乐图⽚与对应⽂本
        QJsonObject obj = imageList[i].toObject();
        item->setText(obj.value("text").toString());
        item->setImage(obj.value("path").toString());
        if(index >= col/2 && row == 2)
        {
            ui->recListDownHLayout->addWidget(item);
        }
        else
        {
            ui->recListUpHLayout->addWidget(item);
        }
        ++index;
    }
}

